package com.pig.easy.bpm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pig.easy.bpm.constant.BpmConstant;
import com.pig.easy.bpm.dto.request.CompanyReqDTO;
import com.pig.easy.bpm.dto.response.CompanyDTO;
import com.pig.easy.bpm.dto.response.ItemDTO;
import com.pig.easy.bpm.dto.response.TreeDTO;
import com.pig.easy.bpm.entity.CompanyDO;
import com.pig.easy.bpm.entityError.EntityError;
import com.pig.easy.bpm.mapper.CompanyMapper;
import com.pig.easy.bpm.service.CompanyService;
import com.pig.easy.bpm.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * <p>
 * 公司表 服务实现类
 * </p>
 *
 * @author pig
 * @since 2020-05-20
 */
@org.apache.dubbo.config.annotation.Service
@Slf4j
public class CompanyServiceImpl extends BeseServiceImpl<CompanyMapper, CompanyDO> implements CompanyService {

    @Autowired
    CompanyMapper companyMapper;

    @Override
    public Result<PageInfo> getListByCondition(CompanyReqDTO companyReqDTO) {

        if (companyReqDTO == null) {
            return Result.responseError(EntityError.ILLEGAL_ARGUMENT_ERROR);
        }
        int pageIndex = CommonUtils.evalInt(companyReqDTO.getPageIndex(), DEFAULT_PAGE_INDEX);
        int pageSize = CommonUtils.evalInt(companyReqDTO.getPageSize(), DEFAULT_PAGE_SIZE);

        PageHelper.startPage(pageIndex, pageSize);
        CompanyDO company = BeanUtils.switchToDO(companyReqDTO, CompanyDO.class);
        company.setValidState(VALID_STATE);
        List<CompanyDTO> processDTOList = companyMapper.getListByCondition(company);
        if (processDTOList == null) {
            processDTOList = new ArrayList<>();
        }
        PageInfo<CompanyDTO> pageInfo = new PageInfo<>(processDTOList);
        return Result.responseSuccess(pageInfo);
    }

    @Override
    public Result<List<ItemDTO>> getCompanyIdAndNameDictList(CompanyReqDTO companyReqDTO) {

        if (companyReqDTO == null) {
            companyReqDTO = new CompanyReqDTO();
        }
        companyReqDTO.setPageSize(MAX_PAGE_SIZE);
        Result<PageInfo> result = getListByCondition(companyReqDTO);
        if (result.getEntityError().getCode() != EntityError.SUCCESS.getCode()) {
            return Result.responseError(result.getEntityError());
        }
        List<CompanyDTO> companyDTOList = result.getData().getList();
        List<ItemDTO> list = new ArrayList<>();
        ItemDTO itemDTO = new ItemDTO();

        for (CompanyDTO companyDTO : companyDTOList) {
            if (companyDTO != null) {
                itemDTO = new ItemDTO(companyDTO.getCompanyName(), companyDTO.getCompanyId());
                list.add(itemDTO);
            }
        }

        return Result.responseSuccess(list);
    }

    @Override
    public Result<CompanyDTO> getCompanyById(Long companyId) {

        if (CommonUtils.evalLong(companyId) < 0) {
            return Result.responseError(EntityError.ILLEGAL_ARGUMENT_ERROR);
        }
        CompanyDO company = new CompanyDO();
        company.setCompanyId(companyId);
        company.setValidState(VALID_STATE);
        QueryWrapper<CompanyDO> entityWrapper = new QueryWrapper<>(company);
        company = companyMapper.selectOne(entityWrapper);

        if (company == null) {
            return Result.responseError(EntityError.DATA_NOT_FOUND_ERROR);
        }
        return Result.responseSuccess(BeanUtils.switchToDTO(company, CompanyDTO.class));
    }

    @Override
    public Result<CompanyDTO> getCompanyByCode(String companyCode) {

        if (CommonUtils.evalLong(companyCode) < 0) {
            return Result.responseError(EntityError.ILLEGAL_ARGUMENT_ERROR);
        }
        CompanyDO company = new CompanyDO();
        company.setCompanyCode(companyCode);
        company.setValidState(VALID_STATE);
        QueryWrapper<CompanyDO> entityWrapper = new QueryWrapper<>(company);
        company = companyMapper.selectOne(entityWrapper);

        if (company == null) {
            return Result.responseError(EntityError.DATA_NOT_FOUND_ERROR);
        }
        return Result.responseSuccess(BeanUtils.switchToDTO(company, CompanyDTO.class));
    }

    @Override
    public Result<Integer> insert(CompanyReqDTO companyReqDTO) {

        if (companyReqDTO == null
                || StringUtils.isEmpty(companyReqDTO.getTenantId())
                || StringUtils.isEmpty(companyReqDTO.getCompanyCode())) {
            return Result.responseError(EntityError.ILLEGAL_ARGUMENT_ERROR);
        }
        // 默认 key 格式   租户 +":" + key
        if (!companyReqDTO.getCompanyCode().startsWith((companyReqDTO.getTenantId()))) {
            companyReqDTO.setCompanyCode(companyReqDTO.getTenantId()
                    + BpmConstant.COMMON_CODE_SEPARATION_CHARACTER
                    + "process"
                    + BpmConstant.COMMON_CODE_SEPARATION_CHARACTER
                    + companyReqDTO.getCompanyCode());
        }
        CompanyDO company = BeanUtils.switchToDO(companyReqDTO, CompanyDO.class);
        Integer num = companyMapper.insert(company);
        return Result.responseSuccess(num);
    }

    @Override
    public Result<Integer> updateByCompanyId(CompanyReqDTO companyReqDTO) {
        if (companyReqDTO == null
                || CommonUtils.evalLong(companyReqDTO.getCompanyId()) < 0) {
            return Result.responseError(EntityError.ILLEGAL_ARGUMENT_ERROR);
        }

        CompanyDO company = BeanUtils.switchToDO(companyReqDTO, CompanyDO.class);
        Integer num = companyMapper.updateById(company);
        return Result.responseSuccess(num);
    }

    @Override
    public Result<Integer> updateByCompanyCode(CompanyReqDTO companyReqDTO) {

        if (companyReqDTO == null
                || StringUtils.isEmpty(companyReqDTO.getCompanyCode())) {
            return Result.responseError(EntityError.ILLEGAL_ARGUMENT_ERROR);
        }

        CompanyDO company = BeanUtils.switchToDO(companyReqDTO, CompanyDO.class);
        Integer num = companyMapper.updateByCompanyCode(company);
        return Result.responseSuccess(num);
    }

    @Override
    public Result<List<TreeDTO>> getCompanyTree(Long parentId, String tenantId) {

        if(CommonUtils.evalLong(parentId) < 0){
            parentId = 0L;
        }
        BestBpmAsset.isEmpty(tenantId);
        CompanyReqDTO companyReqDTO = new CompanyReqDTO();
        companyReqDTO.setPageSize(MAX_PAGE_SIZE);
        companyReqDTO.setTenantId(tenantId);

        Result<PageInfo> result = getListByCondition(companyReqDTO);
        if (result.getEntityError().getCode() != EntityError.SUCCESS.getCode()) {
            return Result.responseError(result.getEntityError());
        }
        List<CompanyDTO> companyDTOList = result.getData().getList();
        List<TreeDTO> list = new ArrayList<>();
        TreeDTO treeDTO = null;

        for (CompanyDTO companyDTO : companyDTOList) {
            if (companyDTO != null) {
                treeDTO = new TreeDTO();
                treeDTO.setId(SnowKeyGenUtils.getInstance().getNextId());
                treeDTO.setTreeId(companyDTO.getCompanyId());
                treeDTO.setTreeCode(companyDTO.getCompanyCode());
                treeDTO.setTreeName(companyDTO.getCompanyName());
                treeDTO.setParentId(companyDTO.getCompanyParentId());
                treeDTO.setTreeTypeCode("company");
                treeDTO.setTreeType(1);
                list.add(treeDTO);
            }
        }
        list = makeTree(list,parentId);

        /* 移除非 */
        Iterator<TreeDTO> iterator = list.iterator();
        while (iterator.hasNext()){
            if(!iterator.next().getParentId().equals(parentId)){
                iterator.remove();
            }
        }
        return Result.responseSuccess(list);
    }

}
